<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * This is a sample module for PyroCMS
 *
 * @author 		Jerel Unruh - PyroCMS Dev Team
 * @website		http://unruhdesigns.com
 * @package 	PyroCMS
 * @subpackage 	Sample Module
 */
class Admin extends Admin_Controller
{
	protected $section = 'message';
	protected $_ci;
	protected $_currentUserGroup;
	protected $_currentUserName = '';
	protected $_curentUserZones;
	protected $_escortIdList;
	public function __construct()
	{
		parent::__construct();

		// Load all the required classes
		$this->load->library('form_validation');
		
		$this->load->model('escort_message_threads_m');
		$this->load->model('escort_messages_m');
		$this->load->model('groups_m');
		$this->_ci = &get_instance();
		$this->lang->load('message');
		$this->lang->load('message_thread');
		// Set the validation rules
		$this->validation_rules = array(
			array(
				'field' => 'message',
				'label' => 'lang:escort_thread_message_label',
				'rules' => 'trim|required|max_length[255]'
			),
			array(
				'field' => 'escort_id',
				'label' => 'lang:escort_thread_solver_label',
				'rules' => 'trim|required|max_length[255]'
			),
			array(
				'field' => 'solver_permission_slug',
				'label' => 'lang:escort_thread_to_label'
			)
		);
		
		$this->_currentUserGroup = $this->_ci->ion_auth->get_user()->group;
		$this->_currentUserName = $this->_ci->ion_auth->get_user()->username;
		$this->_curentUserZones = $this->_ci->escort_user_roles_n_zones_entity->getUserRolesNZones($this->_currentUserName);
		$this->data->escortList = array();
		$this->_escortIdList = $this->_ci->user_entity->getEscortIdListByAdmin($this->_currentUserName, $this->_currentUserGroup, $this->_curentUserZones);
		if($this->_escortIdList){
			$escorts = $this->_ci->escort_entity->getEscortByEscortIdList($this->_escortIdList);
			if($escorts){
				foreach ($escorts as $escort){
					if($escort->escort_name){
						$this->data->escortList[$escort->id] = $escort->escort_name;
					}else{
						$agent = $this->_ci->user_entity->init('id', $escort->user_id);
						$this->data->escortList[$escort->id] = $agent->username;
					}
				}
			}
		}
		$this->template->set_partial('shortcuts', 'admin/partials/shortcuts')
		
						->append_metadata(js('escort.message.js', 'message'))
						->append_metadata(css('escort.message.css', 'message'))
						->append_metadata(js('jquery.simplemodal.js', 'message'))
						->append_metadata(css('osx.css', 'message'));
	}

	/**
	 * List all items
	 */
	public function index()
	{
		$ci = &get_instance();
		$base_where = array('solver_permission_slug' => $ci->ion_auth->get_user()->group, 'status' => 'all');
		if($this->_escortIdList && count($this->_escortIdList) > 0){
			// Create pagination links
			$total_rows = $this->_ci->escort_message_thread_entity->countMessageThreadByEscortIdList($this->_escortIdList, $this->_currentUserGroup);
			$pagination = create_pagination('admin/message/index', $total_rows);
	
			// Using this data, get the relevant results
			$threads = $this->_ci->escort_message_thread_entity->getMessageThreadByEscortIdList($this->_escortIdList, $this->_currentUserGroup,$pagination['limit']);
			if($threads){			
				foreach ($threads as $thread){
					$thread->message = $this->_getLastMessage($thread->id);
				}
			}
		}else{
			$pagination = null;
			$threads = null;
		}
		$groups = $this->groups_m->get_all();
		$groupArray = array();
		if($groups){
			foreach ($groups as $group){
				$groupArray[$group->name] = $group->name;
			}
		}
		$this->data->groupArray = $groupArray;
		
		//do we need to unset the layout because the request is ajax?
		$this->input->is_ajax_request() ? $this->template->set_layout(FALSE) : '';

		$this->template
			->title($this->module_details['name'])
			//->append_metadata(js('admin/filter.js'))
			->set('pagination', $pagination)
			->set('solver_permission_slug', $ci->ion_auth->get_user()->group)
			->set('threads', $threads);

		$this->input->is_ajax_request() ? $this->template->build('admin/tables/posts', $this->data) : $this->template->build('admin/index', $this->data);
			
	}
	
	public function create()
	{
				
		$groups = $this->groups_m->get_all();
		$groupArray = array();
		if($groups){
			foreach ($groups as $group){
				$groupArray[$group->name] = $group->name;		
			}
		}
		$this->data->groupArray = $groupArray;
		$this->form_validation->set_rules($this->validation_rules);

		if ($this->form_validation->run())
		{
			$ci = &get_instance();
			$id = $this->escort_message_threads_m->insert(array(
								'origin'		=> 'admin',
								'owner'		=> $ci->ion_auth->get_user()->username,
								'escort_id'	=>	$this->input->post('escort_id'),
								'solver_permission_slug'		=> $this->input->post('solver_permission_slug'),
								'created_time'		=> time(),
								'status'		=> '0'
			));
			$ci = &get_instance();
			do_log(LOG_ACTION_BACKEND, 0, $ci->ion_auth->get_user()->username, 'escort_log_create_message_action', array($id));
			$this->escort_messages_m->insert(array(
								'sender'		=> $ci->ion_auth->get_user()->username,
								'sent_time'		=> time(),
								'message'		=> $this->input->post('message'),
								'read'		=> 0,
								'thread_id'		=> $id
			))
			? $this->session->set_flashdata('success', sprintf( lang('escort_ads_zone_add_success'), $this->input->post('category')) )
			: $this->session->set_flashdata('error', lang('escort_ads_zone_add_error'));
			
			redirect('admin/message');
		}
		else
		{
			// Go through all the known fields and get the post values
			foreach ($this->validation_rules as $key => $field)
			{
				$post->$field['field'] = set_value($field['field']);
			}
		}

		$this->template
			->title($this->module_details['name'], lang('escort_thread_create_title'))
			->append_metadata($this->load->view('fragments/wysiwyg', $this->data, TRUE))
			->append_metadata(js('jquery/jquery.tagsinput.min.js'))
			->append_metadata(js('blog_form.js', 'blog'))
			->append_metadata(css('jquery/jquery.tagsinput.css'))
			->set('post', $post)
			->build('admin/form', $this->data);
	}
	
	public function delete($id = 0)
	{
		// Delete one
		$ids = ($id) ? array($id) : $this->input->post('action_to');
	
		// Go through the array of slugs to delete
		if ( ! empty($ids))
		{
			$ci = &get_instance();
			foreach ($ids as $id)
			{
				// Get the current page so we can grab the id too
				
				if($this->_currentUserGroup != USER_ADMIN && $this->_currentUserGroup != USER_COUNTRY_MANAGER){
					$thread = $this->escort_message_threads_m->get_thread($id,$ci->ion_auth->get_user()->group);
				}else{
					$thread = $this->escort_message_threads_m->get($id);
				}
				$thread or die();
				if(!in_array($thread->escort_id, $this->_escortIdList)){
					die();
				}
				
				$this->escort_message_threads_m->delete($id);
				
				$this->escort_messages_m->where('thread_id', $id);
				$this->escort_messages_m->delete_by('thread_id', $id);
				
				$ci = &get_instance();
				do_log(LOG_ACTION_BACKEND, 0, $ci->ion_auth->get_user()->username, 'escort_log_delete_message_action', array($id));
				
				// Wipe cache for this model, the content has changed
				$this->pyrocache->delete('escort_message_threads_m');
				$this->pyrocache->delete('escort_messages_m');
				$post_titles[] = $thread->origin;
			
			}
		}
	
		// Some pages have been deleted
		if ( ! empty($post_titles))
		{
			// Only deleting one page
			if (count($post_titles) == 1)
			{
				$this->session->set_flashdata('success', sprintf($this->lang->line('escort_thread_delete_success'), ''));
			}
			// Deleting multiple pages
			else
			{
				$this->session->set_flashdata('success', sprintf($this->lang->line('escort_thread_mass_delete_success'), ''));
			}
		}
		// For some reason, none of them were deleted
		else
		{
			$this->session->set_flashdata('notice', lang('escort_thread_delete_error'));
		}
	
		redirect('admin/message');
	}
	function _getLastMessage($thread_id){
		$this->escort_messages_m->order_by('sent_time ', 'desc');
		return $this->escort_messages_m->get_by('thread_id', $thread_id );
	}
	
	function mark_thread(){
		$thread_id = $this->input->post("thread_id");
		$ci = &get_instance();
		
		//$thread = $this->escort_message_threads_m->get_thread($thread_id,$ci->ion_auth->get_user()->group);
		if($this->_currentUserGroup != USER_ADMIN && $this->_currentUserGroup != USER_COUNTRY_MANAGER){
			$thread = $this->escort_message_threads_m->get_thread($thread_id,$ci->ion_auth->get_user()->group);
		}else{
			$thread = $this->escort_message_threads_m->get($thread_id);
		}
		$thread or die();
		if(!in_array($thread->escort_id, $this->_escortIdList)){
			die();
		}		
		
		$thread or die();
		$result = array();
		if($thread->status){
			$thread->status = 0;
			$result['text'] = lang('escort_thread_mark_as_read_label');
			$result['message'] = lang('escort_message_mark_as_unread_success');
		}else{
			$thread->status = 1;
			$result['text'] = lang('escort_thread_mark_as_unread_label');
			$result['message'] = lang('escort_message_mark_as_read_success');
		}
		if($this->escort_messages_m->where('thread_id', $thread_id)->update_all(array('read'=>$thread->status))){
			$this->escort_message_threads_m->update($thread->id, array('status'=> $thread->status));
			$ci = &get_instance();
			if($thread->status){
				do_log(LOG_ACTION_BACKEND, 0, $ci->ion_auth->get_user()->username, 'escort_log_mark_as_read_message_action', array($thread->id));
			}else{
				do_log(LOG_ACTION_BACKEND, 0, $ci->ion_auth->get_user()->username, 'escort_log_mark_as_unread_message_action', array($thread->id));
			}
			$result['result'] = true;
		}else{
			$result['result'] = false;
			$result['message'] = lang('escort_message_mark_error');
		}
		echo json_encode($result);
	}
	public function action()
	{
		switch ($this->input->post('btnAction'))
		{			
			case 'delete':
				$this->delete();
				break;
			default:
				redirect('admin/message');
			break;
		}
	}
	public function escale_to($thread_id){
		$ci = &get_instance();
		if($this->_currentUserGroup != USER_ADMIN && $this->_currentUserGroup != USER_COUNTRY_MANAGER){
			$thread = $this->escort_message_threads_m->get_thread($thread_id,$ci->ion_auth->get_user()->group);
		}else{
			$thread = $this->escort_message_threads_m->get($thread_id);
		}
		$thread or die();
		if(!in_array($thread->escort_id, $this->_escortIdList)){
			die();
		}		
		
		if($this->input->post('escale_to')){
			$solver_permission_slug = $this->input->post("solver_permission_slug");			
			$result = array();
			
			if($this->escort_message_threads_m->where('id', $thread_id)->update_all(array('solver_permission_slug'=>$solver_permission_slug))){
				$this->session->set_flashdata('success', sprintf($this->lang->line('escort_thread_escale_to_success'), ''));
				$ci = &get_instance();
				do_log(LOG_ACTION_BACKEND, 0, $ci->ion_auth->get_user()->username, 'escort_log_escal_message_action', array($thread->id, $thread->solver_permission_slug, $solver_permission_slug));
				$result['result'] = true;
			}else{
				$result['result'] = false;
				$this->session->set_flashdata('notice', lang('escort_thread_escale_to_error'));
			}
			echo json_encode($result);
		}else{
			$groups = $this->groups_m->get_all();
			$groupArray = array();
			if($groups){
				foreach ($groups as $group){
					$groupArray[$group->name] = $group->name;
				}
			}
			$this->data->groupArray = $groupArray;
			$this->template->set_layout(FALSE);
			$this->template
			->set('thread', $thread)
			->build('admin/escale_to', $this->data);
		}
	}
}
